package demo;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Socket 服务端
 * 
 * @author sundy.hu
 * @version 1.0
 * @date 2012-11-28
 * 
 */
public class Server implements Runnable {

	// 服务端口
	private int port;
	// Socket服务端
	private ServerSocket serverSocket;
	// 文件接收存放路径
	private String path;

	// 设置路径
	public void setPath(String path) {
		this.path = path;
	}

	// 设置端口号
	public Server(int port) {
		this.port = port;
	}

	@Override
	public void run() {
		try {
			serverSocket = new ServerSocket(port);
			System.out.println("server startup at " + port);
			while (true) {
				Socket client = serverSocket.accept();
				receive(client);
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}

	}

	public static String data = "";

	// 接收文件
	private void receive(Socket client) {
		if (null != client) {
			try {
				StringBuffer sb = new StringBuffer();
				int len = 0;
				BufferedInputStream input = new BufferedInputStream(
						client.getInputStream());

				String fileName = path + File.separator
						+ System.currentTimeMillis() + ".zip";
				OutputStream output = new FileOutputStream(fileName);
				DataOutputStream dos = new DataOutputStream(output);
				DataInputStream dis = new DataInputStream(input);
				while ((len = dis.read()) != -1) {
					dos.write((char) len);
					if (1024 * 10 == len) {
						dos.flush();
					}
					sb.append((char) len);
				}
				data = sb.toString();
				input.close();
				dis.close();
				dos.flush();
				dos.close();

				output.flush();
				output.close();
				client.close();
				System.out.println(fileName + " receive successful");
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}

}
